package com.zxx.flowerstore.utils.utils;

import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * @ClassName HttpUtils
 * @Author Admin
 * @Date 2021/4/3 8:13
 * @Description HttpUtils
 * @Version 1.0
 */
public class HttpUtils {
    public static String sendPost(String url, Object param) throws Exception {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            //关闭输出流、输入流
            try {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        return result;
    }


    /**
     * 使用post请求  param JSON的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postJSON(String strURL, String params) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }


    /**
     * 使用post请求  param JSON的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postJSONForm(String strURL, String params) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }

    /**
     * 使用post请求  param JSON的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postJSONUTF8(String strURL, String params) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }

    /**
     * 使用post请求  param JSON的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postJSONUTF8Header(String strURL, String params, Map<String,String> headerMap) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            if(!CollectionUtils.isEmpty(headerMap)) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    connection.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }

    /**
     * 提供给日钢调用
     * @param strURL
     * @param params
     * @return
     * @throws Exception
     */
    public static String postJSONtoRG(String strURL, String params) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setConnectTimeout(20000);
            connection.setReadTimeout(30000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }

    /**
     * 使用get请求  param JSON的String形式
     *
     * @param strURL
     * @return
     */
    public static String getJSON(String strURL) throws Exception {

        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection
                .setRequestProperty("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");
        connection.setRequestProperty("Content-Type",
                "plain/text; charset=UTF-8");
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(6000);
        connection.setReadTimeout(6000);
        connection.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                url.openStream()));
        // 返回结果
        String inputline = in.readLine();
        in.close();
        connection.disconnect();
        return inputline;
    }

    /**
     * 使用get请求  param JSON的String形式
     *
     * @param strURL
     * @return
     */
    public static String getJSONTencentMap(String strURL) throws Exception {

        URL url = new URL(strURL);
        String inputline = "";
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(Boolean.TRUE);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(6000);
        connection.setReadTimeout(6000);
        connection.connect();
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            inputline += line + "\n";
        }
        in.close();
        connection.disconnect();
        return inputline;
    }

    /**
     * 使用post请求  param xml的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postXMLGBKHeader(String strURL, String params,Map<String,String> headerMap) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 设置发送数据的格式
            connection.setRequestProperty("Content-Type", "application/xml;charset=GBK");
            if(!CollectionUtils.isEmpty(headerMap)) {
                for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                    connection.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }

    /**
     * 使用post请求  param xml的String形式
     *
     * @param strURL
     * @param params
     * @return
     */
    public static String postXML(String strURL, String params) throws Exception {
        BufferedReader reader = null;
        OutputStreamWriter out = null;
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(strURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 设置请求方式
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(60000);
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            // utf-8编码
            out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
            out.append(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            return res;
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null)
                    out.close();
                if (reader != null)
                    reader.close();
                if(null != connection)
                    connection.disconnect();
            } catch (Exception e) {
                System.out.println("关闭IO异常");
            }
        }
    }


    public static String getRequestGet(Object object){
        Map<String,Object> objectMap = BeanMap.create(object);

        String queryString = "?";
        for (String key : objectMap.keySet()) {
            if(!StringUtils.isEmpty(key) && null != objectMap.get(key)) {
                queryString += key + "=" + objectMap.get(key) + "&";
            }
        }
        // 去掉最后一个空格
        return queryString.substring(0, queryString.length() - 1);
    }


    public static String getPost(Object object){
        Map<String,Object> objectMap = BeanMap.create(object);

        String queryString = "";
        for (String key : objectMap.keySet()) {
            if(!StringUtils.isEmpty(key) && null != objectMap.get(key)) {
                if(!StringUtils.isEmpty(queryString)){
                    queryString += "&";
                }
                queryString += key + "=" + objectMap.get(key);
            }
        }
        // 去掉最后一个空格
        return queryString;
    }
}
